<template>
	<view :class="{'page-box':true,bottom: !disabled, readBottom: status == 'read' }">
		<view v-if="status != 'read'" class="input-box">
			<view class="input-box-title">基础信息</view>
			<view class="input-item">
				<view class="label">内容</view>
				<view class="input-icon">
					<textarea class="input textarea" v-model="form.context" :disabled="disabled" placeholder="请输入内容" :auto-height="true" />
					<!-- <view class="icon hide iconfont icon-youjiantou"></view> -->
				</view>
			</view>
		</view>
		
		<view v-if="status != 'read'" class="input-box img-box">
			<view class="input-box-title">图片</view>
			<view class="upload-com">
				  <view class="img" 
					v-for="(item,index) in form.images"
					:key="index"
				  >
						  <image mode="scaleToFill" :src="item" @click="previewImage(index,'images')"></image>
						  <view 
							class="del" 
							@click.stop="deleteImg(index,'images')"
							v-if="!disabled"
						  ><view class="icon iconfont icon-guanbi1"></view></view>
				  </view>
				  <view class="upload-com-btn" @click="uploadMoreImgs('images')" v-if="!disabled">
						<view class="icon iconfont icon-jiahao1"></view>
				  </view>
			</view>
		</view>
		
		<view v-if="status == 'read'" class="order-item-box">
			<view class="order--item-wrapper" :key="index">
				<uni-swipe-action>
					<!-- 使用插槽 （请自行给定插槽内容宽度）-->
					<uni-swipe-action-item>
						<view class="order-item">
							<view class="createtime">创建时间: {{form.createtime}}</view>
							<view class="baozhuang">内容: {{form.context}}</view>
							<view class="upload-com">
								  <view class="img" 
									v-for="(imgItem,imgIndex) in form.images"
									:key="index"
								  >
										  <image mode="scaleToFill" :src="imgItem" @click="previewImage2(imgIndex,form.images)"></image>
								  </view>
							</view>
						</view>
						
						<template v-slot:right>
							<view class="swipe-btn" v-if="status == 'read'">
								<view class="del-btn" @click.stop="delFun(form.id)">
									删除
								</view>
							</view>
						</template>
					</uni-swipe-action-item>
				</uni-swipe-action>
				
			</view>
		</view>
		
		<view v-if="status == 'read'" class="order-item-box">
			<view class="order--item-wrapper" v-for="(item,index) in form.list" :key="index">
				<uni-swipe-action>
					<!-- 使用插槽 （请自行给定插槽内容宽度）-->
					<uni-swipe-action-item>
						<view class="order-item">
							<view class="createtime">创建时间: {{item.createtime}}</view>
							<view class="baozhuang">内容: {{item.context}}</view>
							<view class="upload-com">
								  <view class="img" 
									v-for="(imgItem,imgIndex) in item.images"
									:key="index"
								  >
										  <image mode="scaleToFill" :src="imgItem" @click="previewImage2(imgIndex,item.images)"></image>
								  </view>
							</view>
						</view>
						
						<template v-slot:right>
							<view class="swipe-btn" v-if="status == 'read'">
								<view class="del-btn" @click.stop="delItemFun(item.id)">
									删除
								</view>
							</view>
						</template>
					</uni-swipe-action-item>
				</uni-swipe-action>
				
			</view>
		</view>
				
		<view class="bottom-btn" v-if="!disabled">
				<button type="primary" class="btn-confirm" size="mini" @click="confirmFun">保存</button>
		</view>
		
		<view v-if="status == 'read'" class="order-item-add-box" @click="addItem">
			<view class="order-item-add">+ 添加播报内容</view>
		</view>
		
		<uni-popup ref="itemPopup" type="bottom" background-color="#fff">
			<view class="input-box">
				<view class="input-item">
					<view class="label"><text class="must">*</text>内容</view>
					<view class="input-icon">
						<input class="input" v-model="listForm.context" placeholder="请输入内容" />
						<view class="icon hide iconfont icon-youjiantou"></view>
					</view>
				</view>
				<view class="input-item">
					<view class="label"><text class="must">*</text>图片</view>
					<view class="upload-com">
						  <view class="img" 
							v-for="(item,index) in listForm.images"
							:key="index"
						  >
								  <image mode="scaleToFill" :src="item" @click="previewImage(index,'images','listForm')"></image>
								  <view 
									class="del" 
									@click.stop="deleteImg(index,'images','listForm')"
									v-if="disabled"
								  ><view class="icon iconfont icon-guanbi1"></view></view>
						  </view>
						  <view class="upload-com-btn" @click="uploadMoreImgs('images','listForm')" v-if="disabled">
								<view class="icon iconfont icon-jiahao1"></view>
						  </view>
					</view>
				</view>
				<view class="input-save-box">
					<view class="input-save" @click="saveItem">保存</view>
				</view>
			</view>
		</uni-popup>
		
	</view>
</template>

<script setup>
	import {
	    onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom
	} from "@dcloudio/uni-app";
	import { ref } from "vue"
	import configure from '@/configure/server/index.js'
	import { CreateToDayBobao, EditToDayBobao, ToDayBobaoDetile, CreateToDayBobaoERji, DelteToDayBobaoERji, DelteToDayBobao } from "@/configure/api/bobao.js"
	import { showErrMsg, showSuccessMsg } from "@/utils/msg";
	import { getUserInfo } from "@/utils/getUserInfo.js"
	import { validatePlusFloatWithTwo } from "@/utils/validate.js";
	import qiniuUploader from "@/utils/qiniuUploader";
	import { useQiniuStore }  from "@/store/qiniu.js"
	
	const qiniuStore = useQiniuStore()
	
	const form = ref({
		id: '',
		context: '',
		images: [],
		userid: ''
	})
	
	const confirmFun = async() => {
		let { 
			id,
			context,
			images,
			userid
		} = form.value;

		let opt = {
			context,
			images: images.join(","),
			userid
		}
		
		if(status.value == 'add'){
			opt.userid = userInfo.value.id
		}else if(status.value == 'edit'){
			opt.id = id
		}
		
		
		if(!context){
			showErrMsg(`请输入内容!`)
			return
		}
		
		if(status.value == 'add'){
			let res = await CreateToDayBobao(opt);
			if(res.code == 200){
				showSuccessMsg("创建成功!");
				uni.navigateBack({
					delta: -1
				});
			}
		} else if(status.value == 'edit'){
			let res = await EditToDayBobao(opt);
			if(res.code == 200){
				showSuccessMsg("编辑成功!");
				uni.navigateBack({
					delta: -1
				});
			}
		}
		
	}
	
	//上传图片
	const uploadImgs = (e) => {   
		if( form.value.images.length > 5 ){
			uni.showToast({
			  title: '只能上传5张图片!',
			  icon: "none"
			});
			return false;
		}
		
		uni.chooseImage({
		  count: 6,
		  sizeType: ['original', 'compressed'],
		  sourceType: ['album', 'camera'],
		  success(resFile) {
	
			const filePath = resFile.tempFiles[0];
			
			qiniuUploader.upload(filePath.path, (res) => {
			
			  form.value.images.push(res.imageURL);
	
			}, (error) => {
			  console.error('error: ' + JSON.stringify(error));
			});
		  }
		});
		
	}
	
	//预览图片
	const previewImage = (index,key,obj) => {
		let images = form.value[key];
		if(obj == 'listForm'){
			images = listForm.value[key];
		}
		uni.previewImage({
			  current:images[index],    //  传 Number H5端出现不兼容 
			  urls: images
		});
	}
	
	//预览图片
	const previewImage2 = (index,images) => {
		uni.previewImage({
			  current:images[index],    //  传 Number H5端出现不兼容 
			  urls: images
		});
	}
	
	//删除图片
	const deleteImg = (index,key,obj) => {
		if(obj == 'listForm'){
			listForm.value[key].splice(index, 1);
		}else{
			form.value[key].splice(index, 1);
		}
	}
	
	
	//上传图片
	const uploadMoreImgs = (key,obj) => {
		let nums = 5
		let imgLen = form.value[key].length
		
		if(obj == 'listForm'){
			imgLen = listForm.value[key].length;
		}
	
		// if( imgLen >= nums ){
		// 	uni.showToast({
		// 	  title: `最多只能上传${nums}张图片!`,
		// 	  icon: "none"
		// 	});
		// 	return false;
		// }
		
		uni.chooseImage({
		  count: nums,
		  sizeType: ['original', 'compressed'],
		  sourceType: ['album', 'camera'],
		  success(resFile) {
	
			const filePaths = resFile.tempFiles;
			let paths = filePaths.map((v)=>uploadQiniuFun(v.path))
			Promise.all(paths).then((files)=>{
				for(let i=0;i<files.length;i++){
					if(files[i]){
						
						if(obj == 'listForm'){
							listForm.value[key].push(files[i])
						}else{
							form.value[key].push(files[i])
						}
					}
				}
			})
			
		  }
		});
		
	}
	
	const uploadQiniuFun = async(path) => {
		return new Promise((resolve,reject)=>{
			qiniuUploader.upload(path, (res) => {
			
			  resolve(qiniuStore.qiniu + res.key);
			
			}, (error) => {
			  console.error('error: ' + JSON.stringify(error));
			});
		})
	}
	
	const initQiniu = () => {
		uni.request({
			url: `${configure.server.host}/qiniu/getToken`,
			success: function (res) {
			  let token = res.data.token;
			  var options = {
				region: 'ECN', // 华东
				uptoken: token, //七牛token
				fileHead: "manage", //上传前缀
				domain: 'https://cdn.yunnanyunyin.com/' //下载前缀
			  };
			  qiniuUploader.init(options);
			}
		})
	}
	
	const ToDayBobaoDetileFun = async () => {
		let res = await ToDayBobaoDetile({id: form.value.id});
			res = res.data;
		let { id,createtime,context,images,createuserid,list } = res
		form.value = {
			id,
			createtime,
			context,
			images: images == '' ? [] : images.split(","),
			userid: createuserid,
			list: list.map(v=>{
				return{
					...v,
					images: v.images ? v.images.split(",") : ''
				}
			})
		}
	}
	
	const status = ref('add')
	const disabled = ref(false)
	const userInfo = ref()
	onLoad((detail)=>{
		let { state,id } = detail
		
		status.value = state
				
		disabled.value = ( state == 'read' )
		
		form.value.id = id
		
		if(state != 'add'){
			ToDayBobaoDetileFun()
		}
				
		initQiniu()
		
		getUserInfo().then((res)=>{
			userInfo.value = res;
		})
	})
	
	onShow(()=>{
		
	})
	
	const copyContext = (text) => {
		wx.setClipboardData({//复制文本
			data: text,
			success: function (res) {
				   wx.showToast({
					 title: '复制成功',
					icon:"none",
					mask:"true"//是否设置点击蒙版，防止点击穿透
				  })
			}
		})
	}
	
	const itemPopup = ref()
	const listForm = ref({
		id: '',
		context: '',
		images: [],
		userid: ''
	})
	const itemStatus = ref('add')
	const addItem = () => {
		itemPopup.value.open()
		itemStatus.value = 'add'
		listForm.value = {
			id: form.value.id,
			context: '',
			images: [],
			userid: userInfo.value.id
		}
	}
	
	const saveItem = async() => {
		let {
			id, 
			context,
			images,
			userid
		} = listForm.value;
		
		if(!context){
			showErrMsg(`请输入内容!`)
			return
		}
		
		let opt = {
			context,
			images: images.join(",")
		}

		if(itemStatus.value == 'add'){
			opt.userid = userid
			opt.id = id
			let res = await CreateToDayBobaoERji(opt);
			if(res.code == 200){
				showSuccessMsg("创建成功!");
				itemPopup.value.close()
				ToDayBobaoDetileFun()
			}
		} else if(itemStatus.value == 'edit'){
			opt.id = id;
			let res = await EditGuige(opt);
			if(res.code == 200){
				showSuccessMsg("编辑成功!");
				itemPopup.value.close()
				ToDayBobaoDetileFun()
			}
		}
	}
	
	const delFun = (id) => {
		uni.showModal({
		    title: '提示',
		    content: '确认删除?',
		    success: async function (res) {
		        if (res.confirm) {
					
					let res = await DelteToDayBobao({id})
					if(res.code == 200){
						showSuccessMsg("删除成功!");
						uni.navigateBack({
							delta: 1
						});
					}
					
		        } else if (res.cancel) {
		            
		        }
		    }
		});
	}
	
	const delItemFun = (id) => {
		uni.showModal({
		    title: '提示',
		    content: '确认删除?',
		    success: async function (res) {
		        if (res.confirm) {
					
					let res = await DelteToDayBobaoERji({id})
					if(res.code == 200){
						showSuccessMsg("删除成功!");
						ToDayBobaoDetileFun()
					}
					
		        } else if (res.cancel) {
		            
		        }
		    }
		});
	}
	
</script>

<style lang="scss">
	.page-box.readBottom{
		padding-bottom: 180rpx;
	}
	.page-box{
		padding-bottom: 50rpx;
		
		.input-box{
			.textarea{
				margin-right: 0!important;
				// line-height: 1.5em;
			}
		}
		
		.img-box{
			margin-top: 30rpx;
		}
		
		.upload-com{
		  display: flex;
		  flex-direction: row;
		  justify-content: flex-start;
		  flex-wrap: wrap;
		  box-sizing: border-box;
		  margin-top: 30rpx;
		  margin-bottom: 0;
		}
		
		.upload-com .img,.upload-com .upload-com-btn{
		  width:120rpx;
		  height:120rpx;
		  border-radius: 8rpx;
		}
		
		.upload-com .img{
		  position: relative;
		  margin-right: 35rpx;
		  margin-bottom: 35rpx;
		}
		
		.upload-com .img image{
		  width:120rpx;
		  height:120rpx;
		}
		
		.upload-com .upload-com-btn{
		  background: #f0f2f7;
		  display: flex;
		  flex-direction: row;
		  justify-content: center;
		  align-items: center;
		}
		
		.upload-com .upload-com-btn .icon{
		  color: #d2dae6;
		  font-size: 30rpx;
		}
		
		.upload-com .del{
		  width: 37rpx;
		  height: 37rpx;
		  font-size: 45rpx;
		  background: var(--mainColor);
		  color:#fff;
		  position: absolute;
		  right:0;
		  top:0;
		  border-radius: 100rpx;
		  transform: translateX(50%) translateY(-50%);
		  @include flex-center();
		  
		  .icon{
			  font-size: 22rpx;
			 color:#fff;
		  }
		}
		
		.order-item-add-box{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: #f9f9f9;
			z-index: 99;
			padding: 30rpx;
			padding-bottom: 40rpx;
			box-sizing: border-box;
			
			.order-item-add{
				width: 100%;
				height: 130rpx;
				border: 1px dashed var(--mainColor);
				border-radius: 8rpx;
				color: var(--mainColor);
				font-size: 26rpx;
				box-sizing: border-box;
				// margin-top: 30rpx;
				@include flex-center();
			}
		}
		
		.order-item-box{
			margin-top: 30rpx;
			.order--item-wrapper{
				margin-bottom: 30rpx;
			}
			.order-item{
				width: 100%;
				padding: 30rpx;
				box-sizing: border-box;
				background-color: #fff;
				border-radius: 8rpx;
				
				.createtime{
					margin-top: 20rpx;
				}
				
				.createtime,.context{
					font-size: 26rpx;
					color: #576987;
					margin-bottom: 20rpx;
				}
			}
		}
	}	
</style>

